import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../viewmodels/music_player_view_model.dart';
import '../../models/play_mode.dart';

/// 播放模式切换组件
/// 支持列表循环、单曲循环、随机播放三种模式
class PlayModeWidget extends StatelessWidget {
  /// 按钮大小
  final double size;

  /// 图标颜色
  final Color? iconColor;

  /// 是否显示模式名称
  final bool showLabel;

  /// 标签样式
  final TextStyle? labelStyle;

  /// 布局方向
  final Axis direction;

  /// 图标和标签间距
  final double spacing;

  const PlayModeWidget({
    Key? key,
    this.size = 24,
    this.iconColor,
    this.showLabel = false,
    this.labelStyle,
    this.direction = Axis.horizontal,
    this.spacing = 8,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<MusicPlayerViewModel>(
      builder: (context, viewModel, child) {
        return ValueListenableBuilder<PlayMode>(
          valueListenable: viewModel.playMode,
          builder: (context, playMode, child) {
            final iconWidget = IconButton(
              icon: Icon(
                playMode.icon,
                color: iconColor ?? Theme.of(context).iconTheme.color,
                size: size,
              ),
              onPressed: viewModel.togglePlayMode,
              tooltip: playMode.displayName,
            );

            if (!showLabel) {
              return iconWidget;
            }

            final labelWidget = Text(
              playMode.displayName,
              style: labelStyle ?? Theme.of(context).textTheme.bodySmall,
            );

            if (direction == Axis.horizontal) {
              return Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  iconWidget,
                  SizedBox(width: spacing),
                  labelWidget,
                ],
              );
            } else {
              return Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  iconWidget,
                  SizedBox(height: spacing),
                  labelWidget,
                ],
              );
            }
          },
        );
      },
    );
  }
}

/// 播放模式选择器组件
/// 提供下拉菜单或弹窗形式的播放模式选择
class PlayModeSelector extends StatelessWidget {
  /// 触发按钮大小
  final double buttonSize;

  /// 按钮颜色
  final Color? iconColor;

  /// 是否使用弹窗形式（否则使用下拉菜单）
  final bool useDialog;

  const PlayModeSelector({
    Key? key,
    this.buttonSize = 24,
    this.iconColor,
    this.useDialog = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<MusicPlayerViewModel>(
      builder: (context, viewModel, child) {
        return ValueListenableBuilder<PlayMode>(
          valueListenable: viewModel.playMode,
          builder: (context, currentMode, child) {
            return IconButton(
              icon: Icon(
                currentMode.icon,
                color: iconColor ?? Theme.of(context).iconTheme.color,
                size: buttonSize,
              ),
              onPressed: () =>
                  _showModeSelector(context, viewModel, currentMode),
              tooltip: currentMode.displayName,
            );
          },
        );
      },
    );
  }

  /// 显示播放模式选择器
  void _showModeSelector(
    BuildContext context,
    MusicPlayerViewModel viewModel,
    PlayMode currentMode,
  ) {
    if (useDialog) {
      _showModeDialog(context, viewModel, currentMode);
    } else {
      _showModeMenu(context, viewModel, currentMode);
    }
  }

  /// 显示播放模式对话框
  void _showModeDialog(
    BuildContext context,
    MusicPlayerViewModel viewModel,
    PlayMode currentMode,
  ) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择播放模式'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: PlayMode.values.map((mode) {
            return ListTile(
              leading: Icon(mode.icon),
              title: Text(mode.displayName),
              trailing: currentMode == mode
                  ? const Icon(Icons.check, color: Colors.green)
                  : null,
              onTap: () {
                viewModel.setPlayMode(mode);
                Navigator.of(context).pop();
              },
            );
          }).toList(),
        ),
      ),
    );
  }

  /// 显示播放模式菜单
  void _showModeMenu(
    BuildContext context,
    MusicPlayerViewModel viewModel,
    PlayMode currentMode,
  ) {
    final RenderBox button = context.findRenderObject() as RenderBox;
    final RenderBox overlay =
        Overlay.of(context).context.findRenderObject() as RenderBox;
    final RelativeRect position = RelativeRect.fromRect(
      Rect.fromPoints(
        button.localToGlobal(Offset.zero, ancestor: overlay),
        button.localToGlobal(button.size.bottomRight(Offset.zero),
            ancestor: overlay),
      ),
      Offset.zero & overlay.size,
    );

    showMenu<PlayMode>(
      context: context,
      position: position,
      items: PlayMode.values.map((mode) {
        return PopupMenuItem<PlayMode>(
          value: mode,
          child: Row(
            children: [
              Icon(mode.icon),
              const SizedBox(width: 12),
              Text(mode.displayName),
              if (currentMode == mode) ...[
                const Spacer(),
                const Icon(Icons.check, color: Colors.green, size: 16),
              ],
            ],
          ),
        );
      }).toList(),
    ).then((selectedMode) {
      if (selectedMode != null) {
        viewModel.setPlayMode(selectedMode);
      }
    });
  }
}
